package com.hoow.shakoow.shake

import android.annotation.SuppressLint
import android.os.*
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.hoow.shakoow.R
import com.hoow.shakoow.ai.data.ReqLookedAdvert
import com.hoow.shakoow.ai.data.ReqToGreet
import com.hoow.shakoow.ai.home.NetworkViewModel
import com.hoow.shakoow.base.BaseActivity
import com.hoow.shakoow.databinding.ActivityToGreetBinding
import com.hoow.shakoow.enums.PageTagEnum
import com.hoow.shakoow.extend.*
import com.hoow.shakoow.shake.adManager.AdsManager
import com.hoow.shakoow.shake.adManager.AdsStateListener
import com.hoow.shakoow.shake.components.dialog.PurchaseTimesDialog
import com.hoow.shakoow.utils.analytics.util.AnalyticsUtil


/** 打招呼页 */
@SuppressLint("CustomSplashScreen")
class ToGreetActivity : BaseActivity() {

    //布局binding
    private lateinit var mActivityBinding: ActivityToGreetBinding

    // 弹框
    private lateinit var mPurchaseTimesDialog: PurchaseTimesDialog

    // 广告
    private lateinit var mAdsManager: AdsManager

    //api接口viewModel
    private val mNetworkViewModel by lazy {
        ViewModelProvider(this)[NetworkViewModel::class.java]
    }

    override fun onBindingViewModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mNetworkViewModel)
        return list
    }

    override fun onBindingViewTag(): String {
        return PageTagEnum.to_greet.name.uppercase()
    }

    override fun onBindingContentView(): View {
        mActivityBinding = ActivityToGreetBinding.inflate(layoutInflater)
        return mActivityBinding.root
    }

    @SuppressLint("SetTextI18n", "SourceLockedOrientationActivity")
    override fun onContentViewBinded() {
        try {
            // 初始化广告模块
            mAdsManager = AdsManager(this)
            mAdsManager.initAdsSdk(object : AdsStateListener {
                override fun onAdsSdkInitCompleted() {
                    // 初始化广告sdk成功
                }

                override fun onRewardAdCompleted(adType: String, amount: String) {
                    // 看广告完成
                    // 记录看完广告
                    val reqLookedAdvert = ReqLookedAdvert(adId = adType)
                    reqLookedAdvert.showLoading = false
                    mNetworkViewModel.saveLookedAdvert(reqLookedAdvert)
                }
            })

            // 初始化广告弹框
            mPurchaseTimesDialog = PurchaseTimesDialog()
            mPurchaseTimesDialog.setOnActionClickListener { action ->
                if (action == PurchaseTimesDialog.ACTION_WATCH_ADS) {
                    println("===> load reward ad")
                    // 看广告
                    mAdsManager.showRewardAds()

                } else if (action == PurchaseTimesDialog.ACTION_PURCHASE) {
                    // 购买
                    startToUserRechargePage()

                } else if (action == PurchaseTimesDialog.ACTION_LOAD_ADS) {
                    println("===> load native ad")
                    // load native ad
                    mAdsManager.showNativeAds(mPurchaseTimesDialog.mViewBinding.myTemplate)
                }
            }

            // 记录看完广告
            mNetworkViewModel.onSaveLookedAdvertLiveData.observe(this) {
                println("===> 记录看完广告")
                toGreetMsg()
            }

            // 打招呼返回
            mNetworkViewModel.onToGreetLiveData.observe(this) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        // 判断是否可摇
                        val canShake = result.canShake ?: ""
                        if (canShake.equals("YES", true)) {
                            println("====跳转回复列表")
                            // 跳转回复列表
                            val shakeId = intent.getStringExtra("shakeId") ?: ""
                            val userId = intent.getStringExtra("userId") ?: ""
                            val params = HashMap<String, String>()
                            params["userId"] = userId
                            params["shakeId"] = shakeId
                            params["sbId"] = result.sbId ?: ""
                            startToUserChatInfoPage(params)

                        } else {
                            // 直接看广告
                            if (!mPurchaseTimesDialog.isVisible) {
                                mPurchaseTimesDialog.show(
                                    supportFragmentManager,
                                    PurchaseTimesDialog::class.java.simpleName
                                )
                            }
                        }
                    }
                }
            }

            // 打招呼
            mActivityBinding.textToGreet.setOnClickListener {
                // 打招呼
                toGreetMsg()

                // 打点：摇一摇
                AnalyticsUtil.saveHitPointInfo(
                    type = "TO_GREE_CLICK",
                    remark = ""
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun toGreetMsg() {
        val msg = mActivityBinding.editYouWantToSay.text.toString().trim()
        val shakeId = intent.getStringExtra("shakeId") ?: ""
        if (msg.isNotBlank() and shakeId.isNotBlank()) {
            mNetworkViewModel.toGreet(
                ReqToGreet(
                    sendMsg = msg,
                    shakeId = shakeId
                )
            )
        } else {
            Toast.makeText(
                this,
                getString(R.string.shake_enter_words_you_want_to_say),
                Toast.LENGTH_SHORT
            ).show()
        }
    }
}